package org.example.pet.config.mq;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.pet.dto.AdoptedEmailDTO;
import org.example.pet.service.UserService;
import org.example.pet.util.SMSUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AdoptedListener {
    @Autowired
    private SMSUtils smsUtils;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "${spring.rabbitmq.config.producer.topic_found_success.queue}"),
                    exchange = @Exchange(value = "${spring.rabbitmq.config.producer.exchange}", type = ExchangeTypes.TOPIC),
                    key = "${spring.rabbitmq.config.producer.topic_found_success.routing_key}"
            )
    )
    public void listener(String message){
        AdoptedEmailDTO adoptedEmailDTO = JSON.parseObject(message, AdoptedEmailDTO.class);
        String toEmail = adoptedEmailDTO.getToEmail();
        String username = adoptedEmailDTO.getUsername();
        
        log.info("接收领养成功消息：{} {}", toEmail, username);
        // 发送邮件
        try {
            smsUtils.sendRegNotifyMail(toEmail, username);
            log.info("发送邮件成功: {}", toEmail);
        }catch (Exception e) {
            log.error("发送邮件失败: {}", toEmail);
            throw e;
        }
    }
}
